package module.scene.view.iso
{
	
	import code.utils.CountdownTimer;
	
	import com.darwin.darwinBitmapEngine.core.Node;
	import com.darwin.darwinBitmapEngine.events.NodeEvent;
	import com.darwin.darwinDisplay.DarBitmapMovieNode;
	import com.darwin.darwinDisplay.DarBitmapMovieNodeEvent;
	import com.darwin.darwinDll.Dll;
	import com.darwin.darwinDll.core.DllItem;
	import com.darwin.darwinIsometric.core.IsoObject;
	import com.darwin.darwinUI.core.UIComponent;
	import com.darwin.darwinUI.manager.UIManager;
	import com.darwin.darwinUtils.BitmapDataTool;
	
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	
	import main.App;
	import main.AppConfig;
	
	import module.building.consts.BuildConst;
	import module.building.event.BuildEvent;
	import module.building.model.dataObj.BuildingObj;
	import module.building.view.buildingProgressBar.BuildingProgressBar;
	import module.building.view.buildingTips.HarvestPanel;
	import module.main.view.ResourceConst;
	import module.scene.consts.SceneConst;
	import module.scene.model.dataObj.IsoDataObj;
	import module.scene.view.iso.base.JusticeIsoObject;
	import module.scene.view.nodes.TipNode;
	
	
	/**
	 *	建筑场景物件 
	 * @author Roland
	 * 
	 */
	public class BuildingIsoObject extends JusticeIsoObject
	{
		
		private var _node:DarBitmapMovieNode;
		private var _tipNode:TipNode;
		private var _constructionNode:DarBitmapMovieNode;//建造中的建筑
		private var _leftTimeNode:Node;
		private var buildProgress:BuildingProgressBar 
		private var _isShowProgress:Boolean;
		private var offsetDis:int = 10;
		private var _buildWidth:int;
		private var _buildHeight:int;
		
		public function BuildingIsoObject(isoDataObj:IsoDataObj,dataObj:Object = null)
		{
			super(isoDataObj,dataObj);
			fieldVisibleRange = floorWidth*4;
			openFieldVisible = true;
			clickEnabled = true;
			mouseHoverEnabled = true;
			init();
			
		}
		
		private function mouseOutHandler(e:NodeEvent):void {
			if(_leftTimeNode){
				_leftTimeNode.visible = false;
				_isShowProgress = false;
			}
		}
		
		
		/**
		 * 	增加tipNode
		 */		
		public function showTipNode(object:UIComponent, x:int, y:int, type:String):void
		{
			if(_tipNode==null)
			{
				_tipNode = new TipNode(object,type);
				addNode(_tipNode);
			}else{
				_tipNode.source = object;
				_tipNode.tipType = type;
			}
			_tipNode.clickEnabled = true;
			_tipNode.visible = true;
			_tipNode.x = x;
			_tipNode.y = y;
		}
		
		/**
		 *	移除tip
		 */		
		public function hideTipNode():void
		{
			_tipNode.visible = false;
			_tipNode.clickEnabled = false;
		}
		
		private function init():void {
			addEventListener(NodeEvent.MOUSE_CLICK,onClick);
			addEventListener(NodeEvent.MOUSE_OUT,mouseOutHandler);
		}
		
		protected function onClick(event:NodeEvent):void
		{
			if(event.nodeTarget === _tipNode)
			{
				dispatchEvent(new BuildEvent(_tipNode.tipType));
				hideTipNode();
				event.stopPropagation();
			}
		}		
		
		private function onMatComplete(data:Class):void
		{
			if(disposed==true)return;//物件已被销毁,不做后续处理
			if(_node && _node.parentContainer)
			{
				removeNode(_node);
				_node.destroy();
				_node = null;
			}
			_node = new DarBitmapMovieNode(data);
			_node.clickEnabled = true;
			_node.addEventListener(DarBitmapMovieNodeEvent.DARWIN_DRAW_COMPLETE,onDrawComplete);
			addNodeAt(_node,0); 
		}
		
		protected function onDrawComplete(event:DarBitmapMovieNodeEvent):void
		{
			_node.removeEventListener(DarBitmapMovieNodeEvent.DARWIN_DRAW_COMPLETE,onDrawComplete);
			_node.x = _node.offsetPoint.x;
			_node.y = _node.offsetPoint.y;
			_buildWidth = _node.width;
			_buildHeight = _node.height;
			playBuildingMovie();
		}
		
		/**
		 *	播放建筑主体动画 
		 * 
		 */
		private function playBuildingMovie():void
		{
			switch(buildingObj.subType)
			{
				case BuildConst.SUBTYPE_GATE://城门
				{
					_node.gotoAndStop(walkable);//根据walkable设置开关
					break;
				}
				default://其他
				{
					_node.play();
					break;
				}
			}
		}
		
		/**
		 *	停止建筑主体动画 
		 * 
		 */
		private function stopBuildingMovie():void
		{
			switch(buildingObj.subType)
			{
				case BuildConst.SUBTYPE_GATE://城门
				{
					_node.gotoAndStop(walkable);//根据walkable设置开关
					break;
				}
				default://其他
				{
					_node.gotoAndStop(0);
					break;
				}
			}
		}
		
		/**
		 * 检测是否在建造中
		 * 
		 */		
		public function checkIsConstruction():void {
			if(dataObj&&(dataObj as BuildingObj).status==1&&App.stime<(dataObj as BuildingObj).completeTime) {
				if(!buildProgress)buildProgress = new BuildingProgressBar();
				if(!_leftTimeNode){
					_leftTimeNode = new Node();
					addNode(_leftTimeNode);
				}
				var sourceStr:String = ResourceConst.BUILD_CONSTRUCTION_ICON + (dataObj as BuildingObj).size;
				var cla:Class  = Dll.getInstance().getSynPreloadRes("",sourceStr,DllItem.TYPE_SWF);
				if(!_constructionNode){
					_constructionNode = new DarBitmapMovieNode(cla);
					_constructionNode.addEventListener(DarBitmapMovieNodeEvent.DARWIN_DRAW_COMPLETE,function onContructionNode(e:Event):void
					{
						_constructionNode.removeEventListener(DarBitmapMovieNodeEvent.DARWIN_DRAW_COMPLETE,onContructionNode);
						_constructionNode.x = _constructionNode.offsetPoint.x;
						_constructionNode.y= _constructionNode.offsetPoint.y;
					});
				}
				if(_node) {
					stopBuildingMovie();
				}
				
				if(_constructionNode){
					this.addNode(_constructionNode);
					var timer:Timer = new Timer(1000);
					timer.addEventListener(TimerEvent.TIMER,timerHandler);
					timer.start();
					function timerHandler(e:TimerEvent):void {
						var sTime:int = App.stime + 510;
						if(sTime>=(dataObj as BuildingObj).completeTime) {
							buildComplete();
							timer.removeEventListener(TimerEvent.TIMER,timerHandler);
							timer.stop();
							timer = null;
						}else{
							if(_isShowProgress){
								addBuildProgress();
							}
						}
					}
				}
			}
		}
		
		public function showProgress():void {
			if(_leftTimeNode) {
				_isShowProgress = true;
				_leftTimeNode.visible = true;
				addBuildProgress();
			}
		}
		
		/**
		 *  显示进度条
		 * 
		 */		
		private function addBuildProgress():void {
			_leftTimeNode.visible = true;
			buildProgress.progress = (dataObj as BuildingObj).getBuildPorgress();
			buildProgress.setLeftTime((dataObj as BuildingObj).getLeftTime());
			var bitmapData:BitmapData = BitmapDataTool.getBitmapData(buildProgress);
			_leftTimeNode.bitmapData = bitmapData;
			if(_node) {
				_leftTimeNode.y = - _buildHeight/2 - offsetDis;
				_leftTimeNode.x =  - buildProgress.width/2;
			}
		}
		
		/**
		 * 建造完成显示完整建筑 
		 */		
		private function buildComplete():void {
			if(_node) {
				playBuildingMovie();
			}
			if(_leftTimeNode) {
				this.removeNode(_leftTimeNode);
			}
			if(_constructionNode) {
				this.removeNode(_constructionNode);
			}
			(dataObj as BuildingObj).status = 2;
			
			if((dataObj as BuildingObj).subType == BuildConst.SUBTYPE_SHOP 
				&& (dataObj as BuildingObj).status == 2 
				&& isoDataObj && isoDataObj.userId == AppConfig.getInstance().userId)
			{
				trace("++++++++++++++++++++一个自己的商店建造完成+++++++++++++++++++");
				var produceEvent:BuildEvent = new BuildEvent(BuildEvent.PRODUCE);
				var value:Object = {};
				value.eid = eId;
				value.serverId = (_dataObj as BuildingObj).orderArray[0].serverId;
				produceEvent.data = value;
				dispatchEvent(produceEvent);
			}
		}
		
		/**
		 * 生产完毕
		 */		
		private function produceComplete():void
		{
			UIManager.getToolTipManager().hideTips(this);
			(dataObj as BuildingObj).status = 4;
			updateMats();
			var paoPao:UIComponent = new UIComponent();
			paoPao.backgroundSkin = ResourceConst.HARVEST_TIP;
			paoPao.backgroundAuto = true;
			showTipNode(paoPao, 0, -75, BuildEvent.HARVEST_CLICK);
		}
		
		override public function set isoDataObj(value:IsoDataObj):void
		{
			var $walkableChanged:Boolean;
			if(this.walkable != value.walkable)
			{
				$walkableChanged = true;
			}
			super.isoDataObj = value;
			if(isCombo){//可拼接建筑 根据更改的ISODATAOBJ改变显示
				updateMats();
			}else if($walkableChanged)//可通行状态改变
			{
				updateMats();
			}
		}
		
		override public function set dataObj(value:Object):void
		{
			//记录下建筑的原等级与新等级
			var oldLevel:int=0;
			var newLevel:int=0;
			//生产状态
			var oldStatus:int = 0;
			var newStatus:int = 0;
			if(super.dataObj && super.dataObj.level){
				oldLevel = super.dataObj.level;
				oldStatus = super.dataObj.status;
			}
			if(value && value.level){
				newLevel = value.level;
				newStatus = value.status
			}
			
			super.dataObj = value;
			//处理层级关系
			switch(buildingObj.subType)
			{
				case BuildConst.SUBTYPE_RODE://道路
				{
					this.layerIndex = 0;
					break;
				}
				default:
				{
					this.layerIndex = 1;
					break;
				}
			}
			checkIsConstruction();
			checkIsProducing();
			if(_isoDataObj)
			{
				if(oldLevel != newLevel || oldStatus != newStatus){				
					updateMats();
				}
			}
	
		}
		
		/**
		 * 检测是否在生产中 
		 */		
		private function checkIsProducing():void{
			if(buildingObj.currentOrderArr && buildingObj.currentOrderArr.length > 0)
			{
				var produceTimer:Timer = new Timer(1000);
				produceTimer.addEventListener(TimerEvent.TIMER,produceTimerHandler);
				produceTimer.start();
				function produceTimerHandler(e:TimerEvent):void
				{
					var sTime:int = App.stime;
					if(sTime < buildingObj.currentOrderArr[0].produce_complete_time) 
					{
						buildingObj.status = 3;
					}
					else
					{
						produceComplete();
						produceTimer.removeEventListener(TimerEvent.TIMER,produceTimerHandler);
						produceTimer.stop();
						produceTimer = null;
					}
				}
			}
		}
		
		/**
		 * 更新建筑的素材
		 */
		private function updateMats():void{
			Dll.getInstance().getMatRes(_serverId,onMatComplete,getMaterialName(),0,DllItem.TYPE_SWF);
		}
		
		private function getMaterialName():String
		{
			var status:String;
			if(buildingObj.status == 1)
			{
				status = "IDLE";
			}
			else if(buildingObj.status == 2)
			{
				status = "IDLE";
			}
			else if(buildingObj.status == 3)
			{
				status = "PRODUCTING";
			}
			else if(buildingObj.status == 4)
			{
				status = "HARVEST";
			}
			else if(buildingObj.status == 5)
			{
				status = "INJURY";
			}
			else
			{
				status = "RUINS";
			}
			
			if(parts)
			{
				_isoDataObj.partId = parts.indexOf(this)+1;
			}
			
			if(_isoDataObj.isCombo)//自动拼接(如：城墙)
			{
				return "MATERIAL_"+ _serverId +"_LEVEL"+buildingObj.level+"_"+ status + "_" + _isoDataObj.comboRim;
			}else if(_isoDataObj.partId > 0)//组合部件(如：城门)
			{
				return "MATERIAL_"+ _serverId +"_LEVEL"+buildingObj.level+"_"+ status + "_PART" + _isoDataObj.partId;
			}else{
				return "MATERIAL_"+ _serverId +"_LEVEL"+buildingObj.level+"_"+ status;
			}
		}
		
		
		private function get buildingObj():BuildingObj
		{
			return dataObj as BuildingObj;
		}
		
		override public function set comboRim(v:String):void
		{
			if(comboRim != v)
			{
				super.comboRim = v;
				isoDataObj.comboRim = v;
				updateMats();
			}
		}
		
		override public function dispose():void
		{
			super.dispose();
			removeEventListener(NodeEvent.MOUSE_CLICK,onClick);
			removeEventListener(NodeEvent.MOUSE_OUT,mouseOutHandler);
			if(_node)
			{
				_node.destroy();
				_node = null;
			}
			if(_constructionNode)
			{
				if(_constructionNode.parentContainer)
				{
					removeNode(_constructionNode);
				}
				_constructionNode.destroy();
				_constructionNode = null;
			}
			if(_leftTimeNode)
			{
				if(_leftTimeNode.parentContainer)
				{
					removeNode(_leftTimeNode);
				}
				_leftTimeNode = null;
			}
			if(_tipNode)
			{
				if(_tipNode.parentContainer)
				{
					removeNode(_tipNode);
				}
				_tipNode = null;
			}
		}
		

	}
}